import Vue from 'vue'
import store from '@/store'

function saveBaseImgFile(imagename, base64, suffix) {
  //#ifdef APP-PLUS
  return new Promise((rsv, rjc) => {
    const bitmap = new plus.nativeObj.Bitmap("base64");
    bitmap.loadBase64Data(base64, function() {
      const url = "_doc/images/" + imagename + "." + suffix;  

      // 保存 bitmap 图片 到本地 path  
      // bitmap.save( path, options, successCallback, errorCallback ) 4个全必填  
      bitmap.save(url, {  
        overwrite: true, // 是否覆盖  
        // quality: 'quality'  // 图片清晰度  
      }, (success) => {  
        rsv(url) 
        bitmap.clear() // 销毁Bitmap图片  
      }, (error) => {
        rjc()
        bitmap.clear()  
      });
    },
    (err) => {
      console.log('err', err)
      bitmap.clear()
      rjc()
    })
  })
  //#endif
}
 
export const uploader = async function({file_key, file_path, file_path_type}) {
  file_path_type = file_path_type || 'blob'

  if (file_path_type === 'base64') {
      try {
          // file_path = file_path.substring(file_path.indexOf(',') + 1)
          file_path = await saveBaseImgFile('dada', file_path, 'webp')
      } catch (e){
          console.log(e)
      }
  }
  console.log('fpppppp', file_path)
  const res = await Vue.prototype.$u.api.sys.getUploadForm({
    file_key
  })
  if (res.code !== 200) throw new Error('系统异常')
  
  
  console.log('filepath', file_path)
  return new Promise((resolve, reject) => {
    console.log(store, store.state.vuex_token)
    uni.uploadFile({
      url: res.data.new_action,
      filePath: file_path,
      name: 'file',
      formData: res.data.fields,
      header: {
        Authorization: store.state.vuex_token
      },
      success: (ures) => {
        try {
          console.log(ures)
          const r = JSON.parse(ures.data)
          resolve(r.service_url + r.key)
        } catch (e) {
          console.log(e, 'err')
          resolve(res.data.new_action + res.data.fields.key)
        }
      },
      fail (res) {
        console.log('upload fail:', res)
      }
    })
  })
}